from rest_framework import  serializers

from goods.models import SKU


class CartSerializer(serializers.Serializer):
    """
    购物车数据序列化器
    """
    sku_id = serializers.IntegerField(label='sku编号', min_value=1)
    count = serializers.IntegerField(label='数量', min_value=1)
    selected = serializers.BooleanField(label='是否勾选', default=True)

    def validate(self, attrs):
        sku_id = attrs['sku_id']
        count = attrs['count']

        # 检验商品是否存在
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('该商品不存在')

        # 检验购买数量是否大于库存量
        if count > sku.stock:
            raise serializers.ValidationError('库存不足')

        return attrs


class CartSKUSerializer(serializers.ModelSerializer):
    """
    购物车商品数据序列化器
    """
    count = serializers.IntegerField(label='商品数量', min_value=1, read_only=True)
    selected = serializers.BooleanField(label='是否勾选', default=True, read_only=True)

    class Meta:
        model = SKU
        fields = ('id', 'count', 'selected', 'name', 'default_image_url', 'price')


class CartDeleteSerializer(serializers.Serializer):
    """
    删除购物车数据序列化器
    """
    sku_id = serializers.IntegerField(label='sku商品编号', write_only=True, min_value=1)

    def validate_sku_id(self, value):
        """检验商品是否存在"""
        try:
            SKU.objects.get(id=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('该商品不存在')

        return value


class CartSelectAllSerializer(serializers.Serializer):
    """
    购物车全选
    """
    selected = serializers.BooleanField(label='全选')
